package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.App;
import com.ycsj.goldmedalnewconcept.DemoContext;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.ConversationListResq;
import com.ycsj.goldmedalnewconcept.bean.MineBasicInfoResp;
import com.ycsj.goldmedalnewconcept.bean.friendInfo;
import com.ycsj.goldmedalnewconcept.bean.groupInfo;
import com.ycsj.goldmedalnewconcept.bean.mineBasicInfoResp2;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.cehua.DragLayout;
import com.ycsj.goldmedalnewconcept.cehua.DragLayout.DragState;
import com.ycsj.goldmedalnewconcept.cehua.DragLayout.OnDragChangeListener;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.fragment.ClassConversationFragment;
import com.ycsj.goldmedalnewconcept.fragment.ClassConversationNotloginFragment;
import com.ycsj.goldmedalnewconcept.fragment.ClassFragment;
import com.ycsj.goldmedalnewconcept.fragment.GrammarSecondFragment;
import com.ycsj.goldmedalnewconcept.fragment.HomeFragment;
import com.ycsj.goldmedalnewconcept.fragment.ＭessageFragment;
import com.ycsj.goldmedalnewconcept.picture.PhotoInputProvider;
import com.ycsj.goldmedalnewconcept.utils.ConstantValues;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.Utils;
import com.ycsj.goldmedalnewconcept.view.CircleImageView;
import com.ycsj.goldmedalnewconcept.view.MyTabWidget;
import com.ycsj.goldmedalnewconcept.view.MyTabWidget.OnTabSelectedListener;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.IOException;
import java.util.ArrayList;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.GroupInfoProvider;
import io.rong.imkit.RongIM.LocationProvider;
import io.rong.imkit.RongIM.UserInfoProvider;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imkit.widget.provider.LocationInputProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;

/**
 * 金牌君导航页
 *
 * @author dewyze
 *
 */
@SuppressLint("NewApi")
public class JpjMainActivity extends BaseJpStarActivity implements
        OnTabSelectedListener, OnClickListener {

    private static final String TAG = "MainActivity";
    private MyTabWidget mTabWidget;
    private HomeFragment mHomeFragment;
    private ClassFragment mGrammarFragment;
    private ClassConversationFragment mCollectFragment;
    private ClassConversationNotloginFragment mCollectFragment2;
    private ＭessageFragment mSettingFragment;

    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private GrammarSecondFragment mClassSecondFragment;
    private long exitTime = 0;
    private int mIndex = ConstantValues.HOME_FRAGMENT_INDEX;
    private FragmentManager mFragmentManager;
    private FragmentManager fragmentManager;
    private RelativeLayout rl_mine_score;
    private RelativeLayout uc_question;
    private RelativeLayout uc_message;
    private RelativeLayout uc_favor;
    private RelativeLayout uc_address;
    private RelativeLayout uc_about;
    private RelativeLayout rl_checkin;
    private TextView tv_checkin;
    private TextView tv_Username;
    private CircleImageView imageView2;
    private String checkin;
    private DragLayout dl;
    private RadioGroup radioGroup;
    private SystemBarTintManager mTintManager;
    private TextView mUnreadNumView;

    private ArrayList<String> listurl;

    private String path = NetConstant.FRIENDLIST;
    public ArrayList<friendInfo> friendlist = new ArrayList<friendInfo>();
    public ArrayList<UserInfo> UserList = new ArrayList<UserInfo>();
    public ArrayList<Group> GroupList = new ArrayList<Group>();
    private ImageView iv_menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slidemenu_main);
        // //透明状态栏
        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // //透明导航栏
        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.base_color);

        init();
        initEvents();
        DemoContext.init(this);
        initIm();
        onTabSelected(mIndex);
        mTabWidget.setTabsDisplay(this, mIndex);
        mTabWidget.setIndicateDisplay(this, 3, true);
        if (SPUtils
                .getBoolean(JpjMainActivity.this, ConfigConstant.IS_LOGIN_ON)) {

        }
    }

    private void init() {
        mFragmentManager = getSupportFragmentManager();
        mTabWidget = (MyTabWidget) findViewById(R.id.tab_widget);

        // ImageView iv_menu = (ImageView)
        // getFragmentManager().findFragmentByTag("HomeFragment").
        mUnreadNumView = (TextView) findViewById(R.id.de_num);

        rl_checkin = (RelativeLayout) findViewById(R.id.rl_checkin);
        tv_checkin = (TextView) findViewById(R.id.tv_checkin);
        tv_Username = (TextView) findViewById(R.id.textView1);

        imageView2 = (CircleImageView) findViewById(R.id.imageView2);

        iv_menu = (ImageView) findViewById(R.id.iv_menu);
    }

    private void initEvents() {

        mTabWidget.setOnTabSelectedListener(this);
        if (SPUtils
                .getBoolean(JpjMainActivity.this, ConfigConstant.IS_LOGIN_ON)) {
            OkHttpClient mOkHttpClient = new OkHttpClient();
            mOkHttpClient
                    .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            FormEncodingBuilder builder = new FormEncodingBuilder();
            builder.add("userid", SPUtils.getString(JpjMainActivity.this,
                    ConfigConstant.USERNAME));
            builder.add("usertoken", SPUtils.getString(JpjMainActivity.this,
                    ConfigConstant.USERTOKEN));
            Request request = new Request.Builder().url(path)
                    .post(builder.build()).build();

            mOkHttpClient.newCall(request).enqueue(callBackFriendlist);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }



    /**
     * Tab的点击事件
     */
    public void onTabSelected(int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case ConstantValues.HOME_FRAGMENT_INDEX:

                if (null == mHomeFragment) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.center_layout, mHomeFragment);
                } else {
                    mHomeFragment = new HomeFragment();
                    transaction.replace(R.id.center_layout, mHomeFragment);
                }

                break;
            case ConstantValues.CATEGORY_FRAGMENT_INDEX:
                if (null == mGrammarFragment) {
                    mGrammarFragment = new ClassFragment();
                    transaction.add(R.id.center_layout, mGrammarFragment);
                } else {
                    mGrammarFragment = new ClassFragment();
                    transaction.add(R.id.center_layout, mGrammarFragment);
                }

                break;

            case ConstantValues.SETTING_FRAGMENT_INDEX:
                if (null == mSettingFragment) {
                    mSettingFragment = new ＭessageFragment();
                    transaction.add(R.id.center_layout, mSettingFragment);
                } else {
                    mSettingFragment = new ＭessageFragment();
                    transaction.replace(R.id.center_layout, mSettingFragment);
                }
                break;
            case ConstantValues.COLLECT_FRAGMENT_INDEX:

                if (null == mCollectFragment) {
                    if (SPUtils.getBoolean(JpjMainActivity.this,
                            ConfigConstant.IS_LOGIN_ON)) {

                        mCollectFragment = new ClassConversationFragment();
                        transaction.replace(R.id.center_layout, mCollectFragment);
                    } else {
                        mCollectFragment2 = new ClassConversationNotloginFragment();
                        transaction.replace(R.id.center_layout, mCollectFragment2);
                    }

                } else {
                    if (SPUtils.getBoolean(JpjMainActivity.this,
                            ConfigConstant.IS_LOGIN_ON)) {
                        mCollectFragment = new ClassConversationFragment();
                        transaction.replace(R.id.center_layout, mCollectFragment);
                    } else {
                        mCollectFragment2 = new ClassConversationNotloginFragment();
                        transaction.replace(R.id.center_layout, mCollectFragment2);
                    }
                }
                break;
            default:
                break;
        }
        mIndex = index;
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (null != mHomeFragment) {
            // transaction.hide(mHomeFragment);
        }

        if (null != mClassSecondFragment) {
            transaction.hide(mClassSecondFragment);
        }

        if (null != mGrammarFragment) {
            transaction.hide(mGrammarFragment);
        }
        if (null != mCollectFragment) {
            transaction.hide(mCollectFragment);
        }
        if (null != mSettingFragment) {
            transaction.hide(mSettingFragment);
        }
        if (null != mCollectFragment) {
            transaction.hide(mCollectFragment);
        }
        if (null != mCollectFragment2) {
            transaction.hide(mCollectFragment2);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 自己记录fragment的位置,防止activity被系统回收时，fragment错乱的问题
        // super.onSaveInstanceState(outState);
        outState.putInt("index", mIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // super.onRestoreInstanceState(savedInstanceState);
        mIndex = savedInstanceState.getInt("index");
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("PreviewSecondFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("DetectionSecondFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ClassSecondFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            ClassFragment wf = new ClassFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("GrammarFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ClassConversationFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ＭessageFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ClassConversationNotloginFragment".equals(SPUtils
                .getString(this, ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ClassConversationFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("ＭessageFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            mTabWidget.setTabsDisplay(this, 0);
        }

        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("GrammarSecondFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            // Toast.makeText(MainActivity.this, "onKeyDown", 0).show();
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            HomeFragment wf = new HomeFragment();
            // wf.setCurrentItemPosition(1);
            // Bundle args=new Bundle();
            // args.putInt("GRADE_ID", 2001);
            // wf.setArguments(args);
            ft.replace(R.id.center_layout, wf);
            ft.addToBackStack(null);
            ft.commit();
            // mTabWidget.setTabsDisplay(this, 1);
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)
                && ("HomeFragment".equals(SPUtils.getString(this,
                ConfigConstant.CURRENTFRAGMENT)))) {
            if (System.currentTimeMillis() - this.exitTime > 2000L) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                this.exitTime = System.currentTimeMillis();

            } else {
                String rid = SPUtils.getString(JpjMainActivity.this,
                        ConfigConstant.RID);
                // if(SPUtils.getBoolean(MainActivity.this,
                // ConfigConstant.IS_LOGIN_ON)){
                OkHttpClient mOkHttpClient = new OkHttpClient();
                // 创建一个Request
                final Request request = new Request.Builder().url(
                        NetConstant.USERONLINE
                                + "SaveUserOnlineEnd.aspx?rid="
                                + SPUtils.getString(JpjMainActivity.this,
                                ConfigConstant.RID)
                                + "&account="
                                + SPUtils.getString(this,
                                ConfigConstant.USERNAME)).build();
                // new call
                Call call = mOkHttpClient.newCall(request);
                call.enqueue(callBackSystemTimefinish);
                SPUtils.put(JpjMainActivity.this,
                        ConfigConstant.ISAPPONFOREGROUND, false);

                // Log.e("word", NetConstant.USERONLINE+
                // "SaveUserOnlineEnd.aspx?rid="+SPUtils.getString(MainActivity.this,
                // ConfigConstant.RID)
                // +"&account="+
                // SPUtils.getString(this,ConfigConstant.USERNAME));

                // android.os.Process.killProcess(android.os.Process.myPid());

                // }
                // finish();

                //
            }
            return true;
        }
        return false;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_mine_score:

                Intent intent1 = new Intent(JpjMainActivity.this,
                        ScoreSerchActivity.class);
                startActivity(intent1);
                break;
            case R.id.uc_address:

                // Toast.makeText(getActivity(), "班级信息", 0).show();
                // Intent intent2 = new
                // Intent(JpjMainActivity.this,MineInfoActivity.class);
                // startActivity(intent2);
                break;
            case R.id.uc_favor:
                // Toast.makeText(getActivity(), "我的收藏", 0).show();
                Intent intent = new Intent(JpjMainActivity.this,
                        MineShoucangActivity.class);
                startActivity(intent);
                break;
            case R.id.uc_question:
                Uri uri = Uri
                        .parse("http://fusion.qq.com/cgi-bin/qzapps/unified_jump?appid=42285754&from=mqq&actionFlag=0&params=pname%3Dcom.ycsj.goldmedalnewconcept%26versioncode%3D1%26channelid%3D%26actionflag%3D0");
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                // it.setClassName("com.android.browser","com.android.browser.BrowserActivity");
                startActivity(it);
                break;
            case R.id.uc_about:
                Intent intent3 = new Intent(JpjMainActivity.this,
                        AboutActivity.class);
                startActivity(intent3);
                break;
            case R.id.tv_checkin:

                break;

            default:
                break;
        }
    }

    private OnDragChangeListener dragListener = new OnDragChangeListener() {

        @Override
        public void onStateChanged(DragState state) {
            // Toast.makeText(MainActivity.this, state.name(), 0).show();
            if (state == DragState.OPEN) {

                // Toast.makeText(MainActivity.this, "cehua", 0).show();

            } else if (state == DragState.CLOSE) {
                TranslateAnimation ta = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, 1f,
                        Animation.RELATIVE_TO_SELF, 0.5f,
                        Animation.RELATIVE_TO_SELF, 0,
                        Animation.RELATIVE_TO_SELF, 0);
                ta.setDuration(2000);
                ta.setInterpolator(new CycleInterpolator(3));
                // iv_memu.startAnimation(ta);
                // iv_memu.setVisibility(View.VISIBLE);
                // +
                // SPUtils.getString(getActivity(),
                // ConfigConstant.USERTOKEN)

                // Toast.makeText(MainActivity.this, "关闭", 0).show();
            }
        }

        @Override
        public void onDraging(float percent) {
            // ViewHelper.setAlpha(iv_memu, 1- percent);
            // int color = evaluateArgb(percent,Color.BLACK,Color.TRANSPARENT);
            // ((BitmapDrawable)dl.getBackground()).setColorFilter(color,
            // PorterDuff.Mode.SRC_OVER);
        }
    };

    OnCheckedChangeListener listener = new OnCheckedChangeListener() {

        @SuppressLint("NewApi")
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            int index = group.indexOfChild(group.findViewById(checkedId));
            Fragment fragment = fragments.get(index);

            FragmentTransaction ft = getSupportFragmentManager()
                    .beginTransaction();
            ft.addToBackStack(null).replace(R.id.center_layout, fragment)
                    .commit();

        }
    };
    // Callback callBackUsertoken=new Callback() {
    //
    // @Override
    // public void onResponse(Response arg0) throws IOException {
    // String json = arg0.body().string();
    // // 使用Gson把json解析成对象
    // // 1 得到gson对象
    //
    // Log.i("test", "jpjmain=="+json);
    //
    // Gson gson = new Gson();
    // // // 2 使用gson对象的方法
    // IMTokenResq mIMTokenResq = gson.fromJson(json, IMTokenResq.class);
    // // WordLearningResp wordLearningResp = gson.fromJson(json,
    // WordLearningResp.class);
    // // Log.e("items",
    // yuxiResq.QUESTION_LIST.get(1).DETAIL_LIST.get(0).DETAIL_CONTENT);
    //
    // SPUtils.put(JpjMainActivity.this, ConfigConstant.IMTOKEN,
    // mIMTokenResq.token);
    //
    // // connect(SPUtils.getString(MainActivity.this, ConfigConstant.IMTOKEN));
    // /**
    // * 设置会话界面操作的监听器。
    // */
    // RongIM.setConversationBehaviorListener(new
    // MyConversationBehaviorListener());
    // RongIM.setConversationListBehaviorListener(new
    // MyConversationListBehaviorListener());
    // RongIMClient.setConnectionStatusListener(new
    // MyConnectionStatusListener());
    //
    // // RongIM.getInstance().setMessageAttachedUserInfo(true);
    // // connect(mIMTokenResq.token);
    // connect(SPUtil.getString(getApplicationContext(), "token2", ""));
    //
    // RongIM.setUserInfoProvider(new UserInfoProvider() {
    //
    // @Override
    // public UserInfo getUserInfo(String arg0) {
    // String userid=SPUtils.getString(JpjMainActivity.this,
    // ConfigConstant.USERNAME);
    // String username=SPUtils.getString(JpjMainActivity.this,
    // "RongIMusername");
    // String userheadimg=SPUtils.getString(JpjMainActivity.this,
    // "userheadimg");
    // if(userid.equals(arg0)){
    //
    // return new UserInfo(arg0, username, Uri.parse(userheadimg));
    // }
    // return null;
    // }
    // }, true);
    //
    // RongIM.setLocationProvider(new LocationProvider() {
    //
    // @Override
    // public void onStartLocation(Context arg0, LocationCallback arg1) {
    // DemoContext.getInstance().setLastLocationCallback(arg1);
    // // Log.e("test", "onStartLocation");
    // Intent intent = new Intent(JpjMainActivity.this,
    // SOSOLocationActivity.class);
    // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // startActivity(intent);
    // }
    // });
    //
    //
    // //扩展功能自定义
    // InputProvider.ExtendProvider[] provider = {
    // new PhotoInputProvider(RongContext.getInstance()),//图片
    // new CameraInputProvider(RongContext.getInstance()),//相机
    // new LocationInputProvider(RongContext.getInstance()),//地理位置
    // };
    // RongIM.resetInputExtensionProvider(Conversation.ConversationType.PRIVATE,
    // provider);
    // RongIM.resetInputExtensionProvider(Conversation.ConversationType.DISCUSSION,
    // provider);
    // RongIM.resetInputExtensionProvider(Conversation.ConversationType.GROUP,
    // provider);
    // RongIM.resetInputExtensionProvider(Conversation.ConversationType.CUSTOMER_SERVICE,
    // provider);
    //
    //
    // //Log.i("test", "IMTokenResq     "+mIMTokenResq.token);
    //
    // }
    //
    // @Override
    // public void onFailure(Request arg0, IOException arg1) {
    // // TODO Auto-generated method stub
    //
    // }
    // };

    private String rid;
    private RequestCallBack<String> callBackSystemTime = new RequestCallBack<String>() {

        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            // TODO Auto-generated method stub
            String json = responseInfo.result;
            // 使用Gson把json解析成对象
            // 1 得到gson对象

            // Log.i("testtime", json.toString());

            Gson gson = new Gson();
            timeresq fromJson = gson.fromJson(json, timeresq.class);
            rid = fromJson.rid;
            SPUtils.put(JpjMainActivity.this, ConfigConstant.RID, rid);
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            // TODO Auto-generated method stub

        }
    };

    Callback callBackSystemTimefinish = new Callback() {

        @Override
        public void onResponse(Response arg0) throws IOException {
            // TODO Auto-generated method stub
            System.exit(0);
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            // TODO Auto-generated method stub
            System.exit(0);
        }
    };

    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {

        // if
        // (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext())))
        // {

        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {
                // Toast.makeText(MainActivity.this, "服务器连接异常", 0).show();
                // Log.d("LoginActivity", "--onTokenIncorrect");
                reconnect(SPUtils.getString(JpjMainActivity.this,
                        ConfigConstant.IMTOKEN));
            }

            /**
             * 连接融云成功
             *
             * @param userid
             *            当前 token
             */
            @Override
            public void onSuccess(String userid) {
                // Toast.makeText(MainActivity.this, "121", 0).show();
                // Log.d("LoginActivity", "--onSuccess" + userid);
                // startActivity(new Intent(LoginActivity.this,
                // MainActivity.class));
                // finish();

                final Conversation.ConversationType[] conversationTypes = {
                        Conversation.ConversationType.PRIVATE,
                        Conversation.ConversationType.DISCUSSION,
                        Conversation.ConversationType.GROUP,
                        Conversation.ConversationType.SYSTEM,
                        Conversation.ConversationType.PUBLIC_SERVICE,
                        Conversation.ConversationType.APP_PUBLIC_SERVICE };
                RongIM.getInstance().setOnReceiveUnreadCountChangedListener(
                        mCountListener, conversationTypes);
                // RongIM.getInstance().setOnReceiveUnreadCountChangedListener(mCountListener1,
                // Conversation.ConversationType.APP_PUBLIC_SERVICE);

            }

            /**
             * 连接融云失败
             *
             * @param errorCode
             *            错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                // Toast.makeText(MainActivity.this, "131", 0).show();
                // Log.d("LoginActivity", "--onError" + errorCode);
            }
        });
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 重连
     *
     * @param token
     */
    @SuppressLint("NewApi")
    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(App
                .getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    // enterFragment();
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    public RongIM.OnReceiveUnreadCountChangedListener mCountListener = new RongIM.OnReceiveUnreadCountChangedListener() {
        @Override
        public void onMessageIncreased(int count) {
            if (count == 0) {
                mUnreadNumView.setVisibility(View.GONE);
            } else if (count > 0 && count < 100) {
                mUnreadNumView.setVisibility(View.VISIBLE);
                mUnreadNumView.setText(count + "");
            } else {
                mUnreadNumView.setVisibility(View.VISIBLE);
                mUnreadNumView.setText(R.string.no_read_message);
            }
        }

    };

    public RongIM.OnReceiveUnreadCountChangedListener mCountListener1 = new RongIM.OnReceiveUnreadCountChangedListener() {
        @Override
        public void onMessageIncreased(int count) {
            if (count == 0) {
                // mCustomerNoRead.setVisibility(View.GONE);
            } else if (count > 0) {
                // mCustomerNoRead.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // http://moregolden.com:35352/index.html?tel=15333838051
        Log.e("test", "onStoponStoponStop");
    }

    private int grouplist_count;
    Callback callBackFriendlist = new Callback() {

        @Override
        public void onResponse(Response arg0) throws IOException {
            String json = arg0.body().string();

            SPUtils.put(JpjMainActivity.this, "Friendlistjson", json);

            // 使用Gson把json解析成对象
            // 1 得到gson对象

            Log.i("test", "jpjmainj=-=-=" + json);

            Gson gson = new Gson();

            final ConversationListResq mConversationListResq = gson.fromJson(
                    json, ConversationListResq.class);
            friendlist.removeAll(friendlist);

            grouplist_count = mConversationListResq.grouplist_count;
            friendlist.add(0, new friendInfo(mConversationListResq.userid,
                    mConversationListResq.user_headimg,
                    mConversationListResq.user_name));
            try {

                if (mConversationListResq.grouplist != null) {

                    if (mConversationListResq.grouplist.size() > 0) {
                        for (groupInfo groupInfo : mConversationListResq.grouplist) {

                            friendlist.add(1, new friendInfo(groupInfo.groupid,
                                    groupInfo.group_headimg,
                                    groupInfo.group_name));
                            GroupList.add(new Group(groupInfo.groupid,
                                    groupInfo.group_name, Uri
                                    .parse(groupInfo.group_headimg)));

                        }
                        friendlist.addAll(mConversationListResq.friendlist);

                    }

                    // Log.i("test",
                    // "wordLeListInfo     "+mConversationListResq.friendlist.get(0).friend_name);

                    // UserList.add(0,new UserInfo(mConversationListResq.userid,
                    // mConversationListResq.user_name,
                    // Uri.parse(mConversationListResq.user_headimg)));

                    for (friendInfo friendInfo : friendlist) {
                        UserList.add(new UserInfo(friendInfo.friend,
                                friendInfo.friend_name, Uri
                                .parse(friendInfo.friend_headimg)));
                    }

                    // Picasso.with(MainActivity.this).load(mConversationListResq.user_headimg).into(iv_menu);
                    for (UserInfo userInfoRefresh : UserList) {

                        RongIM.getInstance().refreshUserInfoCache(
                                userInfoRefresh);
                    }
                    RongIM.setGroupInfoProvider(new GroupInfoProvider() {

                        @Override
                        public Group getGroupInfo(String arg0) {
                            for (int i = 0; i < GroupList.size(); i++) {
                                if (GroupList.get(i).getId().equals(arg0)) {
                                    // Log.e("test",
                                    // UserList.get(i).getName()+"---="+i);
                                    return GroupList.get(i);
                                }
                            }
                            return null;
                        }
                    }, true);

                    RongIM.setUserInfoProvider(new UserInfoProvider() {

                        @Override
                        public UserInfo getUserInfo(String userId) {
                            for (int i = 0; i < UserList.size(); i++) {
                                if (UserList.get(i).getUserId().equals(userId)) {
                                    // Log.e("test",
                                    // UserList.get(i).getName()+"---="+i);
                                    return UserList.get(i);
                                }
                            }
                            return null;
                        }

                    }, true);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            // TODO Auto-generated method stub

        }
    };
    Callback callBackBascinfo = new Callback() {

        @Override
        public void onResponse(Response arg0) throws IOException {
            String json = arg0.body().string();
            // 使用Gson把json解析成对象
            // 1 得到gson对象

            Log.i("test", json.toString());

            Gson gson = new Gson();
            // // 2 使用gson对象的方法
            if ("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)
                    || "2".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)) {

                SPUtils.put(JpjMainActivity.this, ConfigConstant.IS_LOGIN_ON,
                        false);
                RongIM.getInstance().logout();

            } else if ("没查询到用户基本信息".equals(gson.fromJson(json,
                    mineBasicInfoResp2.class).result)) {
                // rl_main_head.setVisibility(View.GONE);
                // getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_fragment_container,
                // new NotLoggedFragment()).commit();
                SPUtils.put(JpjMainActivity.this, ConfigConstant.IS_LOGIN_ON,
                        false);
                // Intent intent = new Intent(MainActivity.this,
                // LoginActivity.class);
                // startActivity(intent);
                // finish();
            } else {
                final MineBasicInfoResp mineBasicInfoResp = gson.fromJson(json,
                        MineBasicInfoResp.class);
                SPUtils.put(JpjMainActivity.this, ConfigConstant.IS_LOGIN_ON,
                        true);
                SPUtils.put(JpjMainActivity.this, "BascinfoJson", json);

            }
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            if (Utils.checkNetwork(JpjMainActivity.this)) {
                // getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_fragment_container,
                // new NotLoggedFragment()).commit();
                // Intent intent = new
                // Intent(MainActivity.this,NotLoggedActivity.class);
                // startActivity(intent);

                Toast.makeText(JpjMainActivity.this, "网络通讯异常！！！", Toast.LENGTH_SHORT).show();
            } else {
            }
        }
    };

    private void NormalDialogCustomAttr() {

        final NormalDialog dialog = new NormalDialog(this);
        dialog.content("用户账户在其他设备登录")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

            @Override
            public void onBtnLeftClick() {

                // TODO Auto-generated method stub
                // Toast.makeText(WordsYuxiActivit y.this, "right", 0).show();

                dialog.dismiss();

            }
        });
        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

            @Override
            public void onBtnRightClick() {

            }
        });

    }

    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;

    public void setBasIn(BaseAnimatorSet bas_in) {
        this.bas_in = bas_in;
    }

    public void setBasOut(BaseAnimatorSet bas_out) {
        this.bas_out = bas_out;
    }

    private void initIm() {
        /**
         * 设置会话界面操作的监听器。
         */
        connect(SPUtil.getString(JpjMainActivity.this, "token2", ""));

        RongIM.setConversationBehaviorListener(new MyConversationBehaviorListener());
        RongIM.setConversationListBehaviorListener(new MyConversationListBehaviorListener());
        RongIMClient
                .setConnectionStatusListener(new MyConnectionStatusListener());

        RongIM.setLocationProvider(new LocationProvider() {

            @Override
            public void onStartLocation(Context arg0, LocationCallback arg1) {
                DemoContext.getInstance().setLastLocationCallback(arg1);
                // Log.e("test", "onStartLocation");
                Intent intent = new Intent(JpjMainActivity.this,
                        SOSOLocationActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        // 扩展功能自定义
        InputProvider.ExtendProvider[] provider = {
                new PhotoInputProvider(RongContext.getInstance()),// 图片
                new CameraInputProvider(RongContext.getInstance()),// 相机
                new LocationInputProvider(RongContext.getInstance()),// 地理位置
        };
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.PRIVATE, provider);
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.DISCUSSION, provider);
        RongIM.resetInputExtensionProvider(Conversation.ConversationType.GROUP,
                provider);
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.CUSTOMER_SERVICE, provider);

    }

    private class MyConversationListBehaviorListener implements
            RongIM.ConversationListBehaviorListener {

        @Override
        public boolean onConversationClick(Context arg0, View arg1,
                                           UIConversation arg2) {
            Log.e("test", "MyConversationListBehaviorListener");
            // String onUserPortraitClickid =
            // getIntent().getData().getQueryParameter("targetId");

            return false;

        }

        @Override
        public boolean onConversationLongClick(Context arg0, View arg1,
                                               UIConversation arg2) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onConversationPortraitClick(Context arg0,
                                                   ConversationType arg1, String arg2) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onConversationPortraitLongClick(Context arg0,
                                                       ConversationType arg1, String arg2) {
            // TODO Auto-generated method stub
            return false;
        }

    }

    private class MyConversationBehaviorListener implements
            RongIM.ConversationBehaviorListener {

        /**
         * 当点击用户头像后执行。
         *
         * @param context
         *            上下文。
         * @param conversationType
         *            会话类型。
         * @param userInfo
         *            被点击的用户的信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitClick(Context context,
                                           Conversation.ConversationType conversationType,
                                           UserInfo userInfo) {

            // Intent intent = new
            // Intent(JpjMainActivity.this,MineConversationInfo.class);
            // intent.putExtra("userInfo", userInfo.getUserId());
            // SPUtils.put(context, "onUserPortraitClickid",
            // userInfo.getUserId());
            // // Toast.makeText(MainActivity.this, userInfo.getName(),
            // 0).show();
            // startActivity(intent);

            // Log.e("testtime", ""+userInfo.getPortraitUri());

            return true;
        }

        /**
         * 当长按用户头像后执行。
         *
         * @param context
         *            上下文。
         * @param conversationType
         *            会话类型。
         * @param userInfo
         *            被点击的用户的信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitLongClick(Context context,
                                               Conversation.ConversationType conversationType,
                                               UserInfo userInfo) {
            // listurl = new ArrayList<String>();
            // listurl.add(""+userInfo.getPortraitUri());//"http://t2.qlogo.cn/mbloghead/1669d711fcd8498988dc/180.jpg"
            // Intent intent3 = new Intent(JpjMainActivity.this,
            // GetPicShowActivity.class);
            // intent3.putStringArrayListExtra("urllist", listurl);
            // intent3.putExtra("position",0);
            // startActivity(intent3);

            return true;
        }

        /**
         * 当点击消息时执行。
         *
         * @param context
         *            上下文。
         * @param view
         *            触发点击的 View。
         * @param message
         *            被点击的消息的实体信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageClick(Context context, View view,
                                      Message message) {

            // Log.e("test", "onMessageClick   click");
//            if (message.getContent() instanceof ImageMessage) {
//                 Intent intent=new Intent(JpjMainActivity.this,
//                 PhotoActivity.class);
//                 intent.putExtra("message", message);
//                 startActivity(intent);
//                return false;
//            }
            if (message.getContent() instanceof ImageMessage) {
                Intent intent=new Intent(JpjMainActivity.this,
                        PhotoActivity.class);
                intent.putExtra("message", message);
                startActivity(intent);
                return true;
            }

            if (message.getContent() instanceof LocationMessage) {
                Intent intent = new Intent(context, SOSOLocationActivity.class);
                intent.putExtra("location", message.getContent());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return true;
            }

            return false;
        }

        /**
         * 当长按消息时执行。
         *
         * @param context
         *            上下文。
         * @param view
         *            触发点击的 View。
         * @param message
         *            被长按的消息的实体信息。
         * @return 如果用户自己处理了长按后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLongClick(Context context, View view,
                                          Message message) {
            return false;
        }

        /**
         * 当点击链接消息时执行。
         *
         * @param context
         *            上下文。
         * @param link
         *            被点击的链接。
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLinkClick(Context context, String link) {
            return false;
        }

    }

    private class MyConnectionStatusListener implements
            RongIMClient.ConnectionStatusListener {

        @Override
        public void onChanged(ConnectionStatus connectionStatus) {

            switch (connectionStatus) {

                case CONNECTED:// 连接成功。
                    Log.e("testlogin", "连接成功");
                    break;
                case DISCONNECTED:// 断开连接。
                    Log.e("testlogin", "断开连接");
                    break;
                case CONNECTING:// 连接中。
                    Log.e("testlogin", "连接中");
                    break;
                case NETWORK_UNAVAILABLE:// 网络不可用。
                    Log.e("testlogin", "网络不可用");
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT:// 用户账户在其他设备登录，本机会被踢掉线
                    Log.e("testlogin", "用户账户在其他设备登录，本机会被踢掉线");
                    // NormalDialogCustomAttr();
                    break;
            }
        }
    }

}